package com.i2works.smartluolong.manage.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;

/**
 * 数据源配置
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2017/11/28 10:24
 */

//@Configuration
//@EnableTransactionManagement
@Deprecated
public class MybatisConfiguration implements TransactionManagementConfigurer {

    //日志
    private static final Logger logger = LoggerFactory.getLogger(MybatisConfiguration.class);

    @Autowired
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //添加mapper.xml
            bean.setMapperLocations(resolver.getResources("classpath*:**/smartluolong/web/dal/mapper/**/*Mapper.xml"));
            logger.info("加载Mapper.xml文件成功....");
            //添加config.xml
            bean.setConfigLocation(resolver.getResource("classpath:config/mybatis-config.xml"));
            //指定别名包路径
            bean.setTypeAliasesPackage("com.i2works.smartluolong.web.entity");
            //必须添加springbootVFS，否则会引起mybatis找不到实体别名错误
            bean.setVfs(SpringBootVFS.class);
            return bean.getObject();
        } catch (Exception e) {
            logger.error("MybatisAutoConfig异常：" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}
